﻿using JsonConversion;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;
using RTracker.Models.Common;
using RTracker.Models.ErrorLog;
using System.Web.Security;

namespace RTracker.Areas.Recruitment.Models.Client
{
    public class MClient
    {
        /// static variable RowSize  from config settings to get list of this row size.
        public static int nRowSize = Convert.ToInt32(ConfigurationManager.AppSettings["TotalRecordsInListCalling"]);

        /// <summary>
        /// This method is used to create a client in the database.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCClient">This object contains details of the client.</param>
        /// <returns>CStatus which is an object that contain transaction details</returns>
        public CStatus CreateClient(CAuthenticationContext objCAuthenticationContext, ref CClient objCClient)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_create_client_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@client_name", SqlDbType.NVarChar).Value = objCClient.ClientName;
                    cmd.Parameters.Add("@client_desc", SqlDbType.NChar).Value = objCClient.ClientDesc;
                    cmd.Parameters.Add("@organization_id", SqlDbType.Int).Value = objCClient.OrganizationId;
                    cmd.Parameters.Add("@contact_address", SqlDbType.NVarChar).Value = objCClient.ContactAddress;
                    cmd.Parameters.Add("@client_logo", SqlDbType.NVarChar).Value = objCClient.ClientLogo;
                    cmd.Parameters.Add("@website", SqlDbType.NVarChar).Value = objCClient.Website;
                    cmd.Parameters.Add("@industry", SqlDbType.NVarChar).Value = objCClient.Industry;
                    cmd.Parameters.Add("@client_manager", SqlDbType.NVarChar).Value = objCClient.ClientManager;
                    cmd.Parameters.Add("@contract_doc", SqlDbType.VarBinary).Value = null;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCAuthenticationContext.UserId;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// This method is used to delete a client in the database.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCClient">This object contains details of the client.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus DeleteClient(CAuthenticationContext objCAuthenticationContext, ref CClient objCClient)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_delete_client_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCAuthenticationContext.UserId;
                    cmd.Parameters.Add("@client_ids", SqlDbType.NVarChar).Value = objCClient.ClientIds;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// This method is used to update the client's detail in the database.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCClient">This object contains details of the client.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus UpdateClient(CAuthenticationContext objCAuthenticationContext, ref CClient objCClient)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_update_client_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@client_id ", SqlDbType.Int).Value = objCClient.ClientId;
                    cmd.Parameters.Add("@client_name", SqlDbType.NVarChar).Value = objCClient.ClientName;
                    cmd.Parameters.Add("@organization_id", SqlDbType.Int).Value = objCClient.OrganizationId;
                    cmd.Parameters.Add("@client_desc", SqlDbType.NChar).Value = objCClient.ClientDesc;
                    cmd.Parameters.Add("@contact_address", SqlDbType.NVarChar).Value = objCClient.ContactAddress;
                    cmd.Parameters.Add("@client_logo ", SqlDbType.NVarChar).Value = objCClient.ClientLogo;
                    cmd.Parameters.Add("@website", SqlDbType.NVarChar).Value = objCClient.Website;
                    cmd.Parameters.Add("@industry", SqlDbType.NVarChar).Value = objCClient.Industry;
                    cmd.Parameters.Add("@client_manager", SqlDbType.NVarChar).Value = objCClient.ClientManager;
                    cmd.Parameters.Add("@contract_doc", SqlDbType.VarBinary).Value = null;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCAuthenticationContext.UserId;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// This method is used to get the client's detail in the database.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCClient">This object contains details of the client.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus GetClientDetail(CAuthenticationContext objCAuthenticationContext, ref CClient objCClient)
        {
            CStatus oCStatus = new CStatus();
            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand("r_get_client_detail_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Parameters.Add("@client_id", SqlDbType.Int).Value = objCClient.ClientId;
                    //cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    //cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;

                    SqlDataAdapter adp = new SqlDataAdapter(cmd);

                    DataTable dt = new DataTable();

                    int rowsAffected = adp.Fill(dt);

                    if (rowsAffected > 0)
                    {
                        objCClient = dt.ConvertToListFromDataTableClient()[0];
                    }

                    //if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    //{
                    //    oCStatus.Success = true;
                    //    oCStatus.StatusDetails = CAppConstants.DetailSuccess;
                    //}
                    //else
                    //{
                    //    oCStatus.Success = false;
                    //    oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    //}
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// Sets the softlock on the record whose Id is passed.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCClient">This object contains details of the client.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus SetClientSoftLock(CAuthenticationContext objCAuthenticationContext, CClient objCClient)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_set_client_soft_lock_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@client_id", SqlDbType.Int).Value = objCClient.ClientId;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCAuthenticationContext.UserId;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// Sets the hardlock on the record whose Id is passed.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCClient">This object contains details of the client.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus SetClientHardLock(CAuthenticationContext objCAuthenticationContext, CClient objCClient)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_set_client_hard_lock_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@client_id", SqlDbType.Int).Value = objCClient.ClientId;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCAuthenticationContext.UserId;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// Releases the softlock on the record whose Id is passed.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCClient">This object contains details of the client.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus ReleaseClientSoftLock(CAuthenticationContext objCAuthenticationContext, CClient objCClient)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_release_client_soft_lock_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@client_id", SqlDbType.Int).Value = objCClient.ClientId;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCAuthenticationContext.UserId;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// Releases the hardlock on the record whose Id is passed.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCClient">This object contains details of the client.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus ReleaseClientHardLock(CAuthenticationContext objCAuthenticationContext, CClient objCClient)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_release_client_hard_lock_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@client_id", SqlDbType.Int).Value = objCClient.ClientId;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCAuthenticationContext.UserId;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        ///  This function is used to get complete Client list
        /// </summary>
        /// <returns>List of type CClient</returns>
        public GClient GetClientGridList(CClient objCClient, CAuthenticationContext objCAuthenticationContext)
        {
            GClient objGClient = new GClient();
            int nTotalRecords = 0;
            int nCurrentRowSize = nRowSize;

            if (objCClient.RowSize != 0)
            {
                nCurrentRowSize = objCClient.RowSize;
            }
            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand("r_get_candidate_source_paging_list_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@client_id", SqlDbType.Int).Value = objCClient.ClientId;
                    cmd.Parameters.Add("@organization_id", SqlDbType.Int).Value = objCClient.OrganizationId;
                    cmd.Parameters.Add("@page_number", SqlDbType.Int).Value = objCClient.PageNumber;
                    cmd.Parameters.Add("@row_size", SqlDbType.Int).Value = nCurrentRowSize;
                    cmd.Parameters.Add("@sort_on", SqlDbType.VarChar).Value = objCClient.SortOn;
                    cmd.Parameters.Add("@sort_type", SqlDbType.VarChar).Value = objCClient.SortType;
                    cmd.Parameters.Add("@search", SqlDbType.VarChar).Value = objCClient.Search;
                    cmd.Parameters.Add("@searchon", SqlDbType.VarChar).Value = objCClient.SearchOn;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    SqlDataAdapter adp = new SqlDataAdapter(cmd);

                    DataTable dt = new DataTable();

                    int rowsAffected = adp.Fill(dt);

                    objGClient.Paging = new CPaging();
                    if (rowsAffected > 0)
                    {
                        objGClient.LstClient = dt.ConvertToListFromDataTableClient();
                        objGClient.LstClient[0].PageNumber = int.Parse(cmd.Parameters["@idOut"].Value.ToString());
                        objGClient.Paging.PageNumber = objGClient.LstClient[0].PageNumber;
                    }
                    else
                    {
                        objGClient.LstClient = null;
                    }


                    nTotalRecords = int.Parse(cmd.Parameters["@error"].Value.ToString());

                    objGClient.Status = new CStatus();

                    if (nTotalRecords < 0)
                    {
                        objGClient.Status.Success = false;
                        objGClient.Status.StatusDetails = nTotalRecords.DbError();
                    }
                    else
                    {
                        objGClient.Paging.TotalRecordsCount = nTotalRecords;
                        objGClient.Paging.PageSize = nCurrentRowSize;

                        objGClient.Status.Success = true;
                        objGClient.Status.StatusDetails = "success";
                    }
                }
                catch (Exception ex)
                {
                    objGClient.Status = new CStatus();
                    objGClient.Status.Success = false;
                    objGClient.Status.StatusDetails = ex.Message;
                }
            }
            return objGClient;
        }

        /// <summary>
        ///  This function is used to get complete Client list working under a same organization.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about Client's authentication context.</param>
        /// <param name="objCClient">This object contains details of the Client.</param>
        /// <param name="lstCClient">"out" the list of Clients</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus GetClientList(CAuthenticationContext objCAuthenticationContext, int organizationId, out List<CClient> lstCClient)
        {
            CStatus oCStatus = new CStatus();
            lstCClient = new List<CClient>();
            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_get_Client_list_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@organization_id", SqlDbType.Int).Value = organizationId;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    //cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    //cmd.Parameters["@error"].Direction = ParameterDirection.Output;
                    SqlDataAdapter adp = new SqlDataAdapter(cmd);

                    DataTable dt = new DataTable();

                    int rowsAffected = adp.Fill(dt);

                    if (rowsAffected > 0)
                    {
                        lstCClient.AddRange(dt.ConvertToListFromDataTableClient());
                    }

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                        //oCStatus.StatusDetails = CAppErrorsConstants.SomethingWentWrong;
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }


            return oCStatus;
        }
    }
}